package com.fh.fruit.controller.classify;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.fh.controller.base.BaseController;
import com.fh.fruit.entity.classify.Classify;
import com.fh.fruit.service.classify.ClassifyManager;
import com.fh.util.AppUtil;
import com.fh.util.Jurisdiction;
import com.fh.util.PageData;

import net.sf.json.JSONArray;

@Controller
@RequestMapping(value = "/classify")
public class ClassifyController extends BaseController {

	String menuUrl = "classify.do"; // 菜单地址(权限用)
	@Resource(name = "classifyService")
	private ClassifyManager classifyService;

	/**
	 * 显示分类列表
	 * 
	 * @return
	 */
	@RequestMapping
	public ModelAndView list() throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			String id = (null == pd.get("id") || "".equals(pd.get("id").toString())) ? "0" : pd.get("id").toString();
			List<Classify> classifyList = classifyService.classifyByParentId(Integer.parseInt(id));
			mv.addObject("pd", classifyService.getClassifyById(pd)); // 传入父分类所有信息
			mv.addObject("id", id);
			mv.addObject("MSG", null == pd.get("MSG") ? "list" : pd.get("MSG").toString()); // MSG=change
																							// 则为编辑或删除后跳转过来的
			mv.addObject("classifyList", classifyList);
			mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
			mv.setViewName("farm/classify/classify_list");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 显示分类列表ztree(分类管理)
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/listAllClassify")
	public ModelAndView listAllClassify(Model model,String id)throws Exception{
		ModelAndView mv = this.getModelAndView();
		try{
			if (id != null) {
				id = "0";
			}
			PageData pd = this.getPageData();
			mv.addObject("MSG", null == pd.get("MSG")?"list":pd.get("MSG").toString()); //MSG=change 则为编辑或删除后跳转过来的
			mv.addObject("id",id);
			mv.setViewName("farm/classify/classify_ztree");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * auhor mwc
	 * 
	 * @param response
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toClassifyPage")
	public ModelAndView toClassifyPage(HttpServletResponse response, HttpServletRequest request) {
		ModelAndView view = this.getModelAndView();
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/";
		view.addObject("basePath", basePath);
		view.setViewName("farm/classify/classifySynTree");
		return view;
	}

	@RequestMapping(value = "brandSynByclassifyId")
	public void brandSynByclassifyId(HttpServletResponse response, HttpServletRequest request) {
		String id = request.getParameter("classifyid");
		Integer classifyId = null;
		if (id != null) {
			classifyId = Integer.parseInt(id);
		}
		logBefore(logger, Jurisdiction.getUsername() + "根据商品分类查找 品牌列表");
		PrintWriter out = null;
		try {
			/*
			 * List<PageData> list =
			 * classifyService.brandSynByclassifyId(classifyId);
			 */
			List<Classify> classifyList = classifyService.classifyByParentId(Integer.parseInt(id));
			response.setCharacterEncoding("utf-8");
			out = response.getWriter();
			JSONArray listJson = JSONArray.fromObject(classifyList);
			out.print(listJson);
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * auhor mwc
	 * 
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "classifySynTree")
	public void classifySynTree(HttpServletResponse response, HttpServletRequest request) {
		String id = request.getParameter("id");
		Integer parentId = Integer.parseInt(request.getParameter("parentId"));
		if (id != null) {
			parentId = Integer.parseInt(id);
		}
		logBefore(logger, Jurisdiction.getUsername() + "商品分类异步加载树(Tree)");
		PrintWriter out = null;
		try {
			List<PageData> list = classifyService.selectClassifyByParendId(parentId);
			response.setCharacterEncoding("utf-8");
			out = response.getWriter();
			JSONArray listJson = JSONArray.fromObject(list);
			out.print(listJson);
		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	/**
	 * auhor mwc
	 * 
	 * @param response
	 * @param request
	 */
	@RequestMapping(value = "getClassifyIsP")
	@ResponseBody
	public String getClassifyIsP(HttpServletResponse response, HttpServletRequest request) {
		logBefore(logger, Jurisdiction.getUsername() + "分类等级");
		PageData pd = this.getPageData();
		try {
			int parentId=classifyService.getClassifyIsP(pd);
			if(parentId == 0){
				return "success";
			}else{
				return "failed";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}
	}
	
	/**
	 * 请求新增分类页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/toAdd")
	public ModelAndView toAdd()throws Exception{
		ModelAndView mv = this.getModelAndView();
		try{
			PageData pd = new PageData();
			pd = this.getPageData();
			String id = (null == pd.get("id") || "".equals(pd.get("id").toString()))?"0":pd.get("id").toString();//接收传过来的上级菜单ID,如果上级为顶级就取值“0”
			pd.put("id",id);
			mv.addObject("pds", classifyService.getClassifyById(pd));	//传入父菜单所有信息
			mv.addObject("id", id);					//传入菜单ID，作为子菜单的父菜单ID用
			mv.addObject("MSG", "add");							//执行状态 add 为添加
			mv.setViewName("farm/classify/classify_edit");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 保存菜单信息
	 * @param classify
	 * @return
	 */
	@RequestMapping(value="/add")
	public ModelAndView add(HttpServletRequest request)throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
		logBefore(logger, Jurisdiction.getUsername()+"保存分类");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			classifyService.saveClassify(pd); //保存菜单
		} catch(Exception e){
			logger.error(e.toString(), e);
			mv.addObject("msg","failed");
		}
		mv.setViewName("redirect:/classify.do?MSG='change'&id="+pd.get("parentid")); //保存成功跳转到列表页面
		return mv;
	}
	
	/**
	 * 请求编辑菜单页面
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/toEdit")
	public ModelAndView toEdit(String id)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			pd.put("id",id);				//接收过来的要修改的ID
			pd = (PageData) classifyService.getClassifyById(pd);	//读取此ID的菜单数据
			mv.addObject("pd", pd);				//放入视图容器
			pd.put("id",pd.get("parentid").toString());			//用作读取父菜单信息
			mv.addObject("pds", classifyService.getClassifyById(pd));			//传入父菜单所有信息
			mv.addObject("id", pd.get("parentid").toString());	//传入父菜单ID，作为子菜单的父菜单ID用
			mv.addObject("MSG", "edit");
			pd.put("id",id);			//复原本菜单ID
			mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
			mv.setViewName("farm/classify/classify_edit");
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 保存修改
	 * @return
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit()throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			System.out.println("name=="+pd.getString("name"));
			if(pd!=null){
				classifyService.updateEdit(pd);
			}
			mv.addObject("QX",Jurisdiction.getHC());	//按钮权限
			mv.setViewName("redirect:/classify.do?MSG='change'&id="+pd.get("parentid")); //保存成功跳转到列表页面
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 删除分类
	 * @param id
	 * @param out
	 */
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(@RequestParam String id)throws Exception{
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return null;} //校验权限
		logBefore(logger, Jurisdiction.getUsername()+"删除分类");
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "";
		try{
			if(classifyService.classifyByParentId(Integer.parseInt(id)).size() > 0){//判断是否有子菜单，是：不允许删除
				errInfo = "false";
			}else if(classifyService.getClassGoods(id) >0){
				errInfo = "false1";
			}else{
				classifyService.deleteClassifyById(id);
				errInfo = "success";
			}
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		map.put("result", errInfo);
		return AppUtil.returnObject(new PageData(), map);
	}
	

}
